package com.qf.ts.platform.front.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.ts.platform.front.entity.CarSource;
import com.qf.ts.platform.front.feign.CarSourceCacheServiceClient;
import com.qf.ts.platform.front.feign.CarSourceSearchServiceClient;
import com.qf.ts.platform.front.mapper.CarSourceMapper;
import com.qf.ts.platform.front.service.CarSourceService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author xianchang
 */
@Service
public class CarSourceServiceImpl implements CarSourceService {

    @Resource
    private CarSourceMapper carSourceMapper;

    @Resource
    private CarSourceCacheServiceClient carSourceCacheServiceClient;

    @Resource
    private CarSourceSearchServiceClient carSourceSearchServiceClient;

    @Resource
    private ObjectMapper objectMapper;

    @Override
    public PageInfo<CarSource> getCarSource(CarSource carSource, int page, int pageSize) {
        PageHelper.startPage(page, pageSize);
        return new PageInfo<>(carSourceMapper.getCarSource(carSource));
    }

    @Override
    public void addCarSource(CarSource carSource) {

        int result = carSourceMapper.addCarSource(carSource);

        if (result > 0) {
            try {
                carSourceCacheServiceClient.hMSet("carSource" + carSource.getPlatenum(), carSource);

                //将车源信息通过远程调用或MQ同步到Elasticsearch
                String json = objectMapper.writeValueAsString(carSource);
                carSourceSearchServiceClient.addDocument(json);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    @Override
    public void updateCarSource(CarSource carSource) {
        int result = carSourceMapper.updateCarSource(carSource);

        if (result > 0) {
            try {
                carSourceCacheServiceClient.hMSet("carSource" + carSource.getPlatenum(), carSource);

                //将车源信息通过远程调用或MQ同步到Elasticsearch
                String json = objectMapper.writeValueAsString(carSource);
                carSourceSearchServiceClient.addDocument(json);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void deleteCarSource(Integer id) {
        int result = carSourceMapper.deleteCarSource(id);

        if (result > 0) {
            CarSource carSource = carSourceMapper.getCarSourceById(id);
            try {
                carSourceCacheServiceClient.deleteKey("carSource" + carSource.getPlatenum());

                //TODO:后面需要把该车源信息,同步到网关服务中!可以利用MQ传递消息!
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
